//
//  RecordTaskTableViewCell.m
//  leo
//
//  Created by 常艳 on 15/10/2.
//  Copyright (c) 2015年 mdx. All rights reserved.
//

#import "RecordTaskTableViewCell.h"
#import "GrowManager.h"
#import "LeoMsg.h"
#import "VoiceConverter.h"
#import "AppDelegate.h"
#import "MBFontAdapter.h"
#import "Tooler.h"
@import AVFoundation;
@import AudioToolbox;
@implementation RecordTaskTableViewCell
@synthesize task;
-(void)dealloc
{
    [self removeObservers];
    [self.alertView removeFromSuperview];
    self.alertView.rootViewController=NULL;
    [self.recordView removeFromParentViewController];
    self.task=NULL;
    self.recordView=NULL;
    self.alertView=NULL;
    self.keyWindow=NULL;
    self.timer=NULL;
    self.tb=NULL;
    self.player=NULL;
    
}
- (void)awakeFromNib {
    // Initialization code
    float rate=[UIScreen mainScreen].bounds.size.width/320;
    UIImage *preImg=[UIImage imageNamed:@"record_button_press@2x"];
    [self.recordBtn setImage:preImg forState:UIControlStateHighlighted];
    preImg=NULL;
    self.alertView=[[UIWindow alloc]initWithFrame:CGRectMake(0, 0, 320*rate, 568*rate)];
    self.recordView=[[TaskRecordViewController alloc]init];
    self.keyWindow = [[[UIApplication sharedApplication] delegate] window];
    [self.recordView setMotherWindow:self.alertView];
    self.alertView.rootViewController=self.recordView;
    [self.keyWindow addSubview:self.alertView];
    [self.alertView setWindowLevel:UIWindowLevelAlert];
    [self registerObservers];
}
-(void)initUI
{
//    self.contentView.layer.borderColor =  [UIColor colorWithRed:0.79 green:0.88 blue:0.92 alpha:1].CGColor;
//    self.contentView.layer.borderWidth = 1.0;
    
    if(task==NULL)
        return;
    if(task.title!=NULL&&![task.title isEqualToString:@"(null)"])
        self.titleLable.text=task.title;
    if(task.desc!=NULL&&![task.desc isEqualToString:@"(null)"])
    {
        self.descLable.text=task.desc;
    }
    if (task.createTime != NULL &&![task.createTime isEqualToString:@"(null)"]) {
        self.dateLabel.text = [Tooler getDate:task.createTime];
    }
    self.empLable.text=[NSString stringWithFormat:@"完成后获得%d点经验值",task.empirical];
    if(task.status==DONE)
    {
        self.canRecord=NO;
//        self.statusLable.text=@"完成";
        self.statusImg.hidden = NO;
        self.statusImg.image=[UIImage imageNamed:@"task_already@2x.png"];
        self.recordBtn.enabled=NO;
        self.recordBtn.hidden=YES;
        AppDelegate *mydelegate=[[UIApplication sharedApplication] delegate];
        if(mydelegate!=NULL&&mydelegate.recordTaskCell!=NULL)
        {
            if(mydelegate.recordTaskCell==self)
            {
                self.playBtn.imageView.animationImages=[NSArray arrayWithObjects:
                                                        [UIImage imageNamed:@"voice_g_anim1.png"],
                                                        [UIImage imageNamed:@"voice_g_anim2.png"],
                                                        [UIImage imageNamed:@"voice_g_anim3.png"],                                           nil];
                [self.playBtn.imageView setAnimationDuration:2.0f];
                [self.playBtn.imageView startAnimating];
            }
        }
        
    }
    else if(task.status==UNDO)
    {
        self.canRecord=NO;
//        self.statusLable.text=@"未完成";
        self.statusImg.image=[UIImage imageNamed:@"task_unalready@2x.png"];
        self.recordBtn.enabled=NO;
        self.recordBtn.hidden=YES;
    }
    else if(task.status==EXPIRE||[Tooler istaskExpire:task])
    {
        self.canRecord=NO;
        self.statusLable.text=@"过期";
        self.statusImg.image=[UIImage imageNamed:@"task_timeOut@2x.png"];
        self.recordBtn.enabled=NO;
        self.recordBtn.hidden=YES;
    }
    else if(task.status==DOING)
    {
        self.canRecord=YES;
        self.statusImg.hidden = YES;
//        self.statusLable.text=@"进行中";
//        self.statusImg.image=[UIImage imageNamed:@"grow_label_doing@2x.png"];
        self.recordBtn.enabled=YES;
        self.recordBtn.hidden=NO;
    }
    if(task.audioUrl!=NULL&&![task.audioUrl isEqualToString:@"(null)"]&&![task.audioUrl isEqualToString:@""])
    {
        self.recordImg.hidden=NO;
        self.playBtn.hidden=NO;
        self.timeLable.hidden=NO;
        self.timeLable.text=[NSString stringWithFormat:@"%d",task.duration];
    }
    else
    {
        self.recordImg.hidden=YES;
        self.playBtn.hidden=YES;
        self.timeLable.hidden=YES;
    }
    NSTimer *timer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(timer) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop]addTimer:timer forMode:NSRunLoopCommonModes];


}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch=[touches anyObject];
    CGPoint current=[touch locationInView:self];
    if(self.canRecord==YES &&CGRectContainsPoint(self.recordBtn.frame, current))
    {
        AppDelegate *mydelegate=[[UIApplication sharedApplication] delegate];
        if(mydelegate!=NULL&&mydelegate.recordTaskCell!=NULL)
        {
            [mydelegate.recordTaskCell stop];
            mydelegate.recordTaskCell=NULL;
        }
        if(mydelegate!=NULL&&mydelegate.taskCell!=NULL)
        {
            [mydelegate.taskCell stop];
            mydelegate.taskCell=NULL;
        }
        self.isCancle=NO;
        if(!self.isAdd)
        {
            int res=[self.recordView start];
            if(res==-1)
            {
                self.isAdd=NO;
                return;
            }
            self.isAdd=YES;
            self.recordView.infoLable.text=@"手指上滑，取消发送";
            [self.alertView makeKeyAndVisible];

            self.previous=current;
            if(self.tb!=NULL)
                self.tb.scrollEnabled=NO;
        }
    }
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch=[touches anyObject];
    CGPoint current=[touch locationInView:self];
    if(self.previous.y -current.y>50)
    {
        [self preCancleRecord];
        self.recordView.isCancle=YES;
        self.previous=current;
    }
    if(current.y-self.previous.y>50)
    {
        [self preSendRecord];
        self.recordView.isCancle=NO;
        self.previous=current;
    }
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    if(!self.isAdd)
        return;
    if(!self.isCancle)
    {
        [self stopRecord];
    }
    else
    {
        [self cancleRecord];
    }
    if(self.tb!=NULL)
        self.tb.scrollEnabled=YES;
}
-(void)preSendRecord
{
    self.isCancle=NO;
    self.recordView.isCancle=NO;
    self.recordView.infoLable.text=@"手指上滑，取消发送";
    UIImage *sendImg=[UIImage imageNamed:@"record_anim0@2x"];
    self.recordView.actionImg.image=sendImg;
    sendImg=NULL;
}
- (void)preCancleRecord {
    self.isCancle=YES;
    self.recordView.isCancle=YES;
    self.recordView.infoLable.text=@"松开手指，取消发送";
    self.recordView.actionImg.image=[UIImage imageNamed:@"record_Trash@2x"];
}
- (void)cancleRecord {
    self.alertView.hidden=YES;
    self.isAdd=NO;
    self.isCancle=NO;
    self.recordView.isCancle=NO;
    [self.recordView stop];
    NSString *file_url=[self.recordView getRecordSaveUrl];
    if(file_url==NULL)
    {
        NSLog(@"%@,stopRecord,file_url is null.",recordTask_tag);
        return;
    }
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *err=nil;
    [fileManager removeItemAtPath:file_url error:&err];
    if(err!=nil)
    {
        NSLog(@"%@,cancleRecord,delete file error,error is %@.",recordTask_tag,err);
    }
}
- (void)stopRecord {
    self.isCancle=NO;
    self.recordView.isCancle=YES;
    self.isAdd=NO;
    //录制时间太短
    if([self.recordView getDuration]<1)
    {
        [self.recordView stop];
        self.recordView.infoLable.text=@"录音时间太短";
        self.timer=[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeDown) userInfo:nil repeats:YES];
        return;
    }
    [self.recordView stop];
    self.alertView.hidden=YES;
    
    NSString *file_url=[self.recordView getRecordSaveUrl];
    if(file_url==NULL)
    {
        NSLog(@"%@,stopRecord,file_url is null.",recordTask_tag);
        return;
    }
    NSString *amr_url=[self.recordView getAmrSaveUrl];
    if(amr_url==NULL)
    {
        NSLog(@"%@,stopRecord,file_url is null.",recordTask_tag);
        return;
    }
    if(![VoiceConverter ConvertWavToAmr:file_url amrSavePath:amr_url])
        return;
    if(task==NULL||task.randomCode==NULL)
    {
        NSLog(@"%@,stopRecord,task is null.",recordTask_tag);
        return;
    }
    task.duration=[self.recordView getDuration];
    task.audioUrl=[self.recordView getAudioUrl];
    task.saveUrl=file_url;
    task.audioAmrUrl=[self.recordView getAmrUrl];
    task.saveAmrUrl=amr_url;
    GrowManager *growManager=[[GrowManager alloc] init];
    if(growManager==NULL)
        return;
    [growManager finishTask:task completion:^(SyncResult result, NSDictionary *retValue, NSString *description) {
        if(result==SUCESS)
        {
            self.task.status=DONE;
            [self initUI];
            //删除amr文件
            [self deleteAmrFile:task.saveAmrUrl];
        }
        else
        {
            [Tooler showHttpMsg:result description:description msg:@"完成任务失败"];
        }
    }];
    
}
-(void)deleteAmrFile:(NSString *)file_url
{
    if(file_url==NULL)
    {
        NSLog(@"%@,deleteAmrFile,file_url is null.",recordTask_tag);
        return;
    }
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *err=nil;
    [fileManager removeItemAtPath:file_url error:&err];
    if(err!=nil)
    {
        NSLog(@"%@,deleteAmrFile,delete file error,error is %@.",recordTask_tag,err);
    }
}
-(void)timeDown
{
    self.alertView.hidden=YES;
    [self.timer invalidate];
}
- (IBAction)playRecord:(id)sender {
    [self playAction];
}
-(void)playAction
{
    AppDelegate *mydelegate=[[UIApplication sharedApplication] delegate];
    if(mydelegate!=NULL)
    {
        if(mydelegate.taskCell!=NULL)
        {
            [mydelegate.taskCell stop];
            mydelegate.taskCell=NULL;
        }
        if(mydelegate.recordTaskCell!=NULL&&mydelegate.recordTaskCell!=self)
        {
            [mydelegate.recordTaskCell stop];
            mydelegate.recordTaskCell=NULL;
        }
        mydelegate.recordTaskCell=self;
    }
    if(!self.isPlay)
    {
        self.playBtn.imageView.animationImages=[NSArray arrayWithObjects:
                                                [UIImage imageNamed:@"voice_g_anim1.png"],
                                                [UIImage imageNamed:@"voice_g_anim2.png"],
                                                [UIImage imageNamed:@"voice_g_anim3.png"],                                           nil];
        [self.playBtn.imageView setAnimationDuration:2.0f];
        [self.playBtn.imageView startAnimating];
        [self play:task.audioUrl];
        self.isPlay=YES;
    }
    else
    {
        [self.player stop];
        [self.playBtn.imageView stopAnimating];
        self.playBtn.imageView.animationImages=NULL;
        self.isPlay=NO;
    }
    
}
-(void)play:(NSString *)path
{

    if(path==NULL)
    {
        NSLog(@"%@,play,path is null.",recordTask_tag);
        return;
    }
    path=[[Tooler getDocumentDirectory] stringByAppendingString:path];
    NSLog(@"%@,play,path is %@.",recordTask_tag,path);
    //文件管理器
    NSFileManager *fileManager = [NSFileManager defaultManager];
    //判断数据库是否存在
    BOOL find = [fileManager fileExistsAtPath:path];
    if(find)
    {
        AVAudioSession *audioSession=[AVAudioSession sharedInstance];
        [audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
        [audioSession setActive:YES error:nil];
        NSError *error=nil;
        self.player=[[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL URLWithString:path] error:&error];
        if(error!=nil)
        {
            NSLog(@"%@,playRecord,create player error,error is %@.",recordTask_tag,error);
            return;
        }
        
        [self.player setVolume:1.0];
        self.player.delegate=self;
        self.player.numberOfLoops=0;
        [self.player prepareToPlay];
        [self.player play];
    }
    else
    {
        NSLog(@"%@,playRecord,the record file is not exist.",recordTask_tag);
    }
}
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
    [self stop];
    AppDelegate *mydelegate=[[UIApplication sharedApplication] delegate];
    if(mydelegate!=NULL&&mydelegate.recordTaskCell!=NULL)
    {
        if(mydelegate.recordTaskCell==self)
            mydelegate.recordTaskCell=NULL;
    }
}
-(void)stop
{
    if(self.player!=NULL)
    {
        [self.player stop];
        [self.playBtn.imageView stopAnimating];
        self.playBtn.imageView.animationImages=NULL;
    }
    self.isPlay=NO;
}
-(void)registerObservers
{
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(receiveNotification:) name:RECORDTIMEEXCEED object:nil];
}
-(void)removeObservers
{

    [[NSNotificationCenter defaultCenter] removeObserver:self name:RECORDTIMEEXCEED object:nil];
}
- (void)receiveNotification:(NSNotification *)sender {
    if([sender.name isEqualToString:RECORDTIMEEXCEED])
    {
        [self stopRecord];
    }
}


@end
